package structure;

import java.io.File;
import java.util.Hashtable;
import java.util.Set;
import java.util.TreeMap;


public class SectorBuffer {
	
	private final int width,height,BUFFER_SIZE;
	
	private Hashtable<Integer,Sector> buffers = new Hashtable<Integer,Sector>();
	private TreeMap<Integer,Long> lastAccess = new TreeMap<Integer,Long>();
	
	private Sector current;
	private int currentIndex = -1;
	
	private String name;
	
	public SectorBuffer(int width, int height, int BUFFER_SIZE,String name){
		this.width = width/Sector.SIZE+1;
		this.height = height/Sector.SIZE +1;
		this.BUFFER_SIZE = BUFFER_SIZE;
		this.name = name;
		new File(getMapRoot()).mkdirs();
	}
	
	
	public int getIndex(int coord[]){
		int[] tmp = new int[]{coord[0]/Sector.SIZE,coord[1]/Sector.SIZE,coord[2]/Sector.SIZE};
		//System.out.println(width);
		return tmp[0]+tmp[1]*width+tmp[2]*width*height;
	}
	
	public Sector getSector(int coord[]){
		int index = getIndex(coord);
		if(currentIndex != index){
			currentIndex = index;
			
			if(buffers.get(index)==null)
				load(coord);
			
			current = buffers.get(index);
		}
		lastAccess.put(currentIndex, System.currentTimeMillis());
		return current;
	}
	
	private void load(int coord[]){
		int index = getIndex(coord);
		
		if(buffers.size() >= BUFFER_SIZE){
			//Remove the oldest sector (so the one with the smallest time
			int remove = lastAccess.keySet().iterator().next();
			//save the change in the sector
			try {
				//j'ai changer un truc...... remove 2 X
				buffers.get(remove).writeSector(getFileName(remove));
			} catch (Exception e) {
				e.printStackTrace();
			}
			buffers.remove(remove);
			lastAccess.remove(remove);
		}
		
		try {
			if(new File(getFileName(index)).exists()){
				buffers.put(index, Sector.readSector(getFileName(index)));
			}else{
				buffers.put(index, new Sector(coord));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void save() throws Exception{
		Set<Integer> keySet = buffers.keySet();
		for(int index : keySet){
			buffers.get(index).writeSector(getFileName(index));
		}
	}
	
	private String getFileName(int index){
		return getMapRoot()+index+".sct";
	}
	
	private String getMapRoot(){
		return "./map/"+name+"/";
	}
	

}
